package jmine.tec.report.impl.table;

import java.io.Serializable;
import java.math.BigDecimal;

import jmine.tec.report.api.table.ReportCell;
import jmine.tec.report.api.table.ReportColumn;
import jmine.tec.report.api.table.ReportTableGroupCell;

/**
 * Célula de grupo de relatório capaz de efetuar a somatória de uma coluna de um elemento de um grupo.
 * 
 * @param <V> tipo de registro
 * @author lundberg
 */
public class ReportTableGroupSum<V> implements ReportTableGroupCell<V>, Serializable {

    private final ReportColumn<V> column;

    private BigDecimal sum;

    private final Integer decimals;

    /**
     * Construtor
     * 
     * @param column column
     * @param decimals decimals
     */
    public ReportTableGroupSum(ReportColumn<V> column, Integer decimals) {
        this.column = column;
        this.sum = BigDecimal.ZERO;
        this.decimals = decimals;
    }

    /**
     * {@inheritDoc}
     */
    public ReportCell createCell() {
        ReportCell cell = new ReportCellImpl(this.sum);
        this.sum = BigDecimal.ZERO;
        cell.setRendererType(ReportTableBuilder.TYPE_NUMBER);
        new RendererParameterInterface(cell).setDecimals(this.decimals);
        return cell;
    }

    /**
     * {@inheritDoc}
     */
    public void processRecord(V record) {
        Object value = this.column.createCell(record).getValue();
        if (value instanceof BigDecimal) {
            this.sum = this.sum.add((BigDecimal) value);
        } else if (value instanceof Number) {
            this.sum = this.sum.add(new BigDecimal(((Number) value).doubleValue()));
        }
    }
}
